<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class Team extends Model
{

    

    

    // 表名
    protected $name = 'team';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
	
	public function plan() {
		return $this->belongsTo('businessPlan', 'business_plan_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 创建战队
	 * @param $planId 活动ID
	 * @param $name 战队名称
	 * @param $userId 创建用户
	 * @param $weixinCode
	 * @param $slogan
	 * @param $image
	 * @param $content
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
	public function createTeam($planId, $name, $userId, $weixinCode, $slogan, $image, $content) {
		$this->startTrans();
		try {
			//添加战队
			$res = $this->isUpdate(false)
				->save([
					'business_plan_id' => $planId,
					'name' => $name,
					'user_id' => $userId,
					'weixin_code' => $weixinCode,
					'slogan' => $slogan,
					'image' => $image,
					'content' => $content
				]);
			
			if(!$res) {
				throw new Exception('创建战队出错');
			}
			
			$teamId = $this->getLastInsID();
			//添加战队成员
			$memberModel = new TeamMember();
			$memberRes = $memberModel->isUpdate(false)
				->save([
					'business_plan_id' => $planId,
					'team_id' => $teamId,
					'user_id' => $userId,
				]);
			if(!$memberRes) {
				throw new Exception('添加战队成员出错');
			}
			
			
			$this->commit();
			return $teamId;
		} catch(Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}




}
